from fastapi import Depends, APIRouter

from apps.system import cruds, schemas
from apps.system.params.dictionary import DictParams, DictDetailParams
from core.auth import Auth, FullAdminAuth
from core.dependencies import IdList
from core.response import SuccessResponse

router = APIRouter(prefix="/dict")


@router.get("/list", summary="获取字典列表")
async def list_dicts(
        params: DictParams = Depends(),
        auth: Auth = Depends(FullAdminAuth(permissions=["system.dict.list"]))
):
    datas, count = await cruds.DictDal(auth.db).get_datas(**params.dict(), v_return_count=True)
    return SuccessResponse(datas, count=count)


@router.post("/create", summary="创建字典")
async def create_dict(
        data: schemas.Dict,
        auth: Auth = Depends(FullAdminAuth(permissions=["system.dict.create"]))
):
    return SuccessResponse(
        await cruds.DictDal(auth.db).create_data(data=data),
        msg="创建成功"
    )


@router.put("/update/{data_id}", summary="更新字典")
async def put_dict(
        data_id: int,
        data: schemas.Dict,
        auth: Auth = Depends(FullAdminAuth(permissions=["system.dict.update"]))
):
    return SuccessResponse(
        await cruds.DictDal(auth.db).put_data(data_id, data),
        msg="修改成功"
    )


@router.delete("/delete", summary="批量删除字典")
async def delete_dict(
        ids: IdList = Depends(),
        auth: Auth = Depends(FullAdminAuth(permissions=["system.dict.delete"]))
):
    await cruds.DictDal(auth.db).delete_datas(ids=ids.ids, v_soft=True)
    return SuccessResponse("删除成功")


@router.get("/detail/list", summary="获取单个字典下的字典标签列表，分页")
async def list_dict_details(
        params: DictDetailParams = Depends(),
        auth: Auth = Depends(FullAdminAuth(permissions=["system.dict.list"]))
):
    datas, count = await cruds.DictDetailDal(auth.db).get_datas(**params.dict(), v_return_count=True)
    return SuccessResponse(datas, count=count)


@router.post("/detail/create", summary="创建字典标签")
async def create_dict_detail(
        data: schemas.DictDetail,
        auth: Auth = Depends(FullAdminAuth(permissions=["system.dict.create"]))
):
    return SuccessResponse(
        await cruds.DictDetailDal(auth.db).create_data(data=data),
        msg="创建成功"
    )


@router.put("/detail/update/{data_id}", summary="更新字典标签")
async def put_dict(
        data_id: int,
        data: schemas.DictDetail,
        auth: Auth = Depends(FullAdminAuth(permissions=["system.dict.update"]))
):
    return SuccessResponse(
        await cruds.DictDetailDal(auth.db).put_data(data_id, data),
        msg="修改成功"
    )


@router.delete("/detail/delete", summary="批量删除字典标签")
async def delete_dict_details(
        ids: IdList = Depends(),
        auth: Auth = Depends(FullAdminAuth(permissions=["system.dict.delete"]))
):
    await cruds.DictDetailDal(auth.db).delete_datas(ids=ids.ids, v_soft=True)
    return SuccessResponse("删除成功")
